package dk.au.transxor.mote;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import dk.au.transxor.message.DirectMessage;
import dk.au.transxor.message.IMessage;
import dk.au.transxor.message.MessageFactory;

public abstract class FileSender {

	protected int moteId;
	protected MoteUart moteUart;
	protected int sendDelay;
	protected int amType;
	private int maxDataLength;

	public FileSender(int amType, int maxDataLength, MoteUart moteUart, int moteId, int sendDelay)
			throws FileNotFoundException {
		
		this.maxDataLength = maxDataLength;
		this.amType = amType;
		this.moteId = moteId;
		this.moteUart = moteUart;
		this.sendDelay = sendDelay;
		
	}
	
	public abstract void sendFile(File file, boolean waitInput);

	protected List<IMessage> readFile(File file) {

		try {

			InputStream fileInfo = new BufferedInputStream(new FileInputStream(file));
			ArrayList<IMessage> messages = new ArrayList<IMessage>((fileInfo.available() / maxDataLength) + 1);

			byte[] bytes = new byte[DirectMessage.numElements_data_field()];
			int bytesRead = 0;
			short sequence = 1;
			int totalFileBytes = fileInfo.available();
			IMessage message = null;
			 
			if(totalFileBytes > 0) {
				ByteBuffer byteBuffer = ByteBuffer.allocate(4);
				byteBuffer.putInt(totalFileBytes);
				System.out.println(String.format("Sending FileSize: %s (0x%s) bytes", totalFileBytes, Integer.toHexString(totalFileBytes)));
				
				message = MessageFactory.createMessage(amType);
				
				message.set_data_seq(sequence);
				message.set_data_field(byteBuffer.array());
				messages.add(message);
				
				sequence++;
			
				bytesRead = fileInfo.read(bytes);

				while (bytesRead != -1) {
	
					message = MessageFactory.createMessage(amType);
	
					message.set_data_seq(sequence);
					message.set_data_field(bytes);
	
					messages.add(message);
	
					sequence++;
					bytesRead = fileInfo.read(bytes);
				}
			}

			fileInfo.close();

			return messages;

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
}
